import { PlusOutlined, SettingOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProFormInstance } from '@ant-design/pro-components';
import {
    FooterToolbar,
    PageContainer,
    ProFormText,
    ProFormTextArea,
    ProTable,
    ProForm,
    ProFormDigit,
} from '@ant-design/pro-components';
import { Button, Drawer, message, Image, Popconfirm, Form } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { queryAttributeList, addAttribute, updateAttribute, removeAttribute, queryDetailByProductIDORType, updateByProductIDType } from '@/services/ant-design-pro/product';
import 'react-quill/dist/quill.snow.css';
import { TableListItem } from '../table-list/data';
import RichTextEditor from '@/components/RichTextEditor';

/**
 * 删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
        await removeAttribute({
            id: selectedRows.map((row) => row.id),
        });
        hide();
        message.success('删除成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

const TableList: React.FC = () => {
    const [uploadUrl, setUploadUrl] = useState<string>('');
    const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
    const [isEditing, setIsEditing] = useState<boolean>(false);
    const [showDetail, setShowDetail] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<TableListItem>();
    const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
    const [activeKey, setActiveKey] = useState<string>('1');
    const formRef = useRef<ProFormInstance>();

    const [settingDrawerVisible, setSettingDrawerVisible] = useState<boolean>(false);
    const settingFormRef = useRef<ProFormInstance>();

    const confirm = async (id: number) => {
        await removeAttribute({ id });
        message.success('删除成功');
        actionRef.current?.reloadAndRest?.();
    };

    const handleAdd = async (fields: TableListItem) => {
        const hide = message.loading('正在添加');
        try {
            await addAttribute({ ...fields, attributeImgurl: uploadUrl, productType: activeKey });
            hide();
            message.success('添加成功');
            return true;
        } catch (error) {
            hide();
            message.error('添加失败，请重试！');
            return false;
        }
    };

    const handleUpdate = async (fields: TableListItem, currentRow?: TableListItem) => {
        const hide = message.loading('正在配置');
        try {
            await updateAttribute({
                ...currentRow,
                ...fields,
                attributeImgurl: uploadUrl,
            });
            hide();
            message.success('配置成功');
            return true;
        } catch (error) {
            hide();
            message.error('配置失败，请重试！');
            return false;
        }
    };

    const columns: ProColumns<TableListItem>[] = [
        {
            title: '属性图片',
            dataIndex: 'attributeImgurl',
            render: (text) => <Image src={text} alt="图片" style={{ width: 90, height: 40 }} />,
            search: false,
            width: 110,
            hidden: true
        },
        {
            title: '标题名称',
            dataIndex: 'attributeName',
            width: 150,
            search: false,
            ellipsis: true,
            render: (dom, entity) => {
                const plainText = document.createElement('div');
                plainText.innerHTML = entity.attributeName;
                const text = plainText.innerText;
                plainText.remove();
                return (
                    <a
                        onClick={() => {
                            setCurrentRow(entity);
                            setIsEditing(true);
                            setDrawerVisible(true);
                            setUploadUrl(entity.attributeImgurl);
                        }}
                    >
                        {text}
                    </a>
                );
            },
        },
        {
            title: '内容描述',
            dataIndex: 'attributeDescrible',
            valueType: 'textarea',
            search: false,
            width: 200,
            ellipsis: true,
            render: (_, record) => {
                const plainText = document.createElement('div');
                plainText.innerHTML = record.attributeDescrible;
                const text = plainText.innerText;
                plainText.remove();
                return text;
            }
        },
        {
            title: '产品类型',
            dataIndex: 'productType',
            valueEnum: {
                1: { text: '免费版' },
                2: { text: '包年版' },
                3: { text: '个性定制版' },
            },
            width: 100,
            hidden: true,
            search: false,
        },
        {
            title: '排序',
            dataIndex: 'sort',
            width: 100,
            ellipsis: true,
            search: false
        },
        {
            title: '操作',
            width: 150,
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="config"
                    onClick={() => {
                        setCurrentRow(record);
                        setIsEditing(true);
                        setDrawerVisible(true);
                        setUploadUrl(record.attributeImgurl);
                    }}
                >
                    编辑
                </a>,
                <Popconfirm
                    key="delete"
                    title="确定删除吗？"
                    onConfirm={() => confirm(record.id)}
                >
                    <a>删除</a>
                </Popconfirm>,
            ],
        },
    ];

    useEffect(() => {
        if (drawerVisible && formRef.current) {
            formRef.current.setFieldsValue(currentRow || {});
        }
    }, [drawerVisible, currentRow]);

    const handleSettingClick = async () => {
        try {
            // 打开抽屉后再设置表单值
            setSettingDrawerVisible(true);
            const detail = await queryDetailByProductIDORType({ productId: 1, productType: activeKey });
            console.log(detail.data, 'detail'); // 确保数据正确
            settingFormRef.current?.setFieldsValue({ ...detail.data });
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    const handleSettingSubmit = async (values: any) => {
        try {
            await updateByProductIDType({ ...values, productId: 1, productType: activeKey });
            message.success('更新成功');
            setSettingDrawerVisible(false);
            actionRef.current?.reload();
        } catch (error) {
            message.error('更新失败，请重试！');
        }
    };

    return (
        <PageContainer header={{ title: '' }}>
            <ProTable<TableListItem>
                headerTitle="属性列表"
                actionRef={actionRef}
                rowKey="id"
                search={false}
                toolBarRender={() => [
                    <Button key="setting" type="primary" onClick={handleSettingClick}>
                        <SettingOutlined /> 设置
                    </Button>,
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            setIsEditing(false);
                            setCurrentRow(undefined);
                            setDrawerVisible(true);
                            setUploadUrl('');
                        }}
                    >
                        <PlusOutlined /> 新建
                    </Button>
                ]}
                toolbar={{
                    menu: {
                        type: 'tab',
                        activeKey: activeKey,
                        items: [
                            { key: '1', label: '免费版' },
                            { key: '2', label: '包年版' },
                            { key: '3', label: '个性定制版' },
                        ],
                        onChange: (key) => {
                            setActiveKey(key as string);
                            actionRef.current?.reloadAndRest();
                        },
                    },
                }}
                request={(params) => queryAttributeList({ ...params, productId: 1, productType: activeKey })}
                columns={columns}
                // rowSelection={{
                //     onChange: (_, selectedRows) => {
                //         setSelectedRows(selectedRows);
                //     },
                // }}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项 &nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            await handleRemove(selectedRowsState);
                            setSelectedRows([]);
                            actionRef.current?.reloadAndRest?.();
                        }}
                    >
                        批量删除
                    </Button>
                </FooterToolbar>
            )}
              <Drawer
                title={isEditing ? "编辑属性" : "新建属性"}
                width={600}
                onClose={() => setDrawerVisible(false)}
                open={drawerVisible}
                destroyOnClose
            >
                <ProForm
                    layout="vertical"
                    formRef={formRef}
                    initialValues={currentRow || {}}
                    onFinish={async (value) => {
                        let success = false;
                        if (isEditing) {
                            success = await handleUpdate(value, currentRow);
                        } else {
                            success = await handleAdd(value);
                        }

                        if (success) {
                            setDrawerVisible(false);
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    }}
                >
                    <Form.Item name="attributeName" label="标题名称" rules={[{ required: true, message: '属性名称必填' }]}>
                        <RichTextEditor
                            value={formRef.current?.getFieldValue('attributeName')}
                            onChange={(value) => formRef?.current?.setFieldsValue({ attributeName: value })}
                        />
                    </Form.Item>
                    <Form.Item name="attributeDescrible" label="标题描述">
                        <RichTextEditor
                            value={formRef.current?.getFieldValue('attributeDescrible')}
                            onChange={(value) => formRef?.current?.setFieldsValue({ attributeDescrible: value })}
                        />
                    </Form.Item>
                    <ProFormDigit
                        label="排序"
                        name="sort"
                    />
                </ProForm>
            </Drawer>
            <Drawer
                title="产品设置"
                width={600}
                open={settingDrawerVisible}
                onClose={() => setSettingDrawerVisible(false)}
                destroyOnClose
            >
                <ProForm
                    layout="vertical"
                    formRef={settingFormRef}
                    onFinish={handleSettingSubmit}
                >   
                      <ProFormText name="typeName" label="产品名称" />
                    <ProFormTextArea name="decrible" label="产品描述" />
                    <ProFormText name="productDuration" label="产品服务时长" />
                </ProForm>
            </Drawer>
        </PageContainer>
    );
};

export default TableList;
